package com.example.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView ivDog;
    private Button btnNext;
    private int[] dogImgs={R.drawable.dog1,R.drawable.dog2,R.drawable.dog3,R.drawable.dog4,R.drawable.dog5};
    private int index= 0;

    private Handler handler;
    private final int MSG_CHANGE_DOG = 1001;
    private boolean isPause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == MSG_CHANGE_DOG){
                    index=(index+1)%dogImgs.length;
                    ivDog.setImageResource(dogImgs[index]);
                    return true;
                }
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(!isPause) {
                        //子线程中不能修改主线程创捷的View
                        //使用消息机制告诉主线程更新解决
                        Message message = new Message();
                        message.what = MSG_CHANGE_DOG;
                        handler.sendMessage(message);
                        Log.e("MainActivity", "send change message");

//                           index=(index+1)%dogImgs.length;
//                           ivDog.setImageResource(dogImgs[index]);
                    }
                }
            }
        }).start();

       ivDog=findViewById(R.id.img_dog);
       btnNext=findViewById(R.id.btn_next);

       btnNext.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               isPause = !isPause;
           }
       });


    }
}
